<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */
declare (strict_types=1);

namespace app\shop_admin\service;

use app\shop_admin\model\Classify;
use app\shop_admin\model\Commodity;
use app\shop_admin\model\Coupon as admin;
use app\shop_admin\model\UserCoupon;
use app\utils\TrimData;
use think\Exception;


/**
 * 优惠券服务
 * @package app\madmin\service
 */
class CouponService
{

    /**
     * 查询列表
     * @param int $page
     * @param int $size
     * @param array $data
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function findAll(array $data, int $page = 1, int $size = 10)
    {
        $admin = admin::field("*");
        $admin = TrimData::searchDataTrim($admin, $data, ['name', 'begin_date', 'end_date']);
        $list = empty($data['id ']) ? $admin
            ->where($data)
            ->paginate(['page' => $page, 'list_rows' => $size]) :
            $admin->where($data)
                ->where('id','IN',$data['id'])
                ->paginate(['page' => $page, 'list_rows' => $size]);
        return [HTTP_SUCCESS, $list];
    }

    /**
     * 保存数据
     * @param array $data
     * @return array
     */
    public function save(array $data)
    {
        $data['limit_value'] = $this->checkLimit($data);
        $model = admin::create($data);
        return [HTTP_CREATED, $model];
    }

    /**
     * 读取一条数据
     * @param int $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function read(int $id)
    {
        $model = admin::find($id);
        return [HTTP_SUCCESS, $model];
    }


    /**
     * 更新数据
     * @param int $id
     * @param array $data
     * @return array
     * @throws Exception
     */
    public function update(int $id, array $data)
    {
        $update_time = $data['update_time'];
        unset($data['update_time']);

        $saveData = [];
        isset($data['total_limit_type'])    && $saveData['total_limit_type']    = $data['total_limit_type'];
        isset($data['total_limit'])         && $saveData['total_limit']         = $data['total_limit'];
        isset($data['user_limit_type'])     && $saveData['user_limit_type']     = $data['user_limit_type'];
        isset($data['user_limit'])          && $saveData['user_limit']          = $data['user_limit'];
        isset($data['status'])              && $saveData['status']              = $data['status'];
        isset($data['is_show'])             && $saveData['is_show']             = $data['is_show'];
        if(isset($saveData['status']) && $saveData['status'] === 1){
            $admin = admin::where('update_time', $update_time)
                ->where('audit',1)
                ->where('id', $id)
                ->save($saveData);
        }else{
            $admin = admin::where('update_time', $update_time)
                ->where('id', $id)
                ->save($saveData);
        }

//        if (empty($admin)) {
//            throw new Exception("修改失败", HTTP_NOTACCEPT);
//        }

        return [HTTP_CREATED, $admin];
    }

    /**
     * @param $id
     * @return int
     */
    public function delete($id)
    {
        admin::destroy($id);
        UserCoupon::destroy(["coupon_id"=>$id]);
        return HTTP_NOCONTEND;
    }

    /**
     * 发送
     * @param int $id
     * @param array $userList
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function send(int $id, array $userList)
    {
        $model = admin::lock(true)->find($id);

        if (empty($model->audit)){
            return [HTTP_NOTACCEPT, '优惠券审核中'];
        }

        if (!$model || $model->status != 1)
            return [HTTP_NOTACCEPT, '优惠券未启用或者数量不够'];

        $residue = bcsub((string)$model->total_limit, (string)$model->used);
        if ($model->total_limit_type == 1 && (count($userList) > $residue))
            return [HTTP_NOTACCEPT, '优惠券数量不够'];

        $data = [];
        foreach ($userList as $k => $v) {
            $data[$k]['user_id'] = $v;
            $data[$k]['coupon_id'] = $id;
            $data[$k]['type'] = 1;
            $data[$k]['used_type'] = $model->used_type;
        }
        $userCoupon = new UserCoupon();
        $userCoupon->saveAll($data);
        $model->inc("used", count($userList))->update();
        return [HTTP_CREATED, "发送成功"];
    }

    public function checkLimit($data)
    {
        $limitValue = null;

        if (!empty($data['commodity_limit'])){
            if ($data['commodity_limit_type'] == 1) {
                $commodityIds = explode(",", $data['commodity_limit']);
                $limitValue = Commodity::where(['id' => $commodityIds])->column("name");
            } elseif ($data['commodity_limit_type'] == 2) {
                $commodityIds = explode(",", $data['commodity_limit']);
                $limitValue = Commodity::where(['id' => $commodityIds])->column("name");
            } elseif ($data['commodity_limit_type'] == 3) {
                $classifyIdList = explode(",", $data['commodity_limit']);
                $classifyIds = array();
                foreach ($classifyIdList as $classifyId) {
                    $explode = explode("->", $classifyId);
                    end($explode);
                    $classifyIds[] = current($explode);
                }
                $limitValue = Classify::where(['id' => $classifyIds])->column("name");
            }
        }

        if(!empty($limitValue))
            $limitValue = implode(",", $limitValue);
        return $limitValue;
    }

}
